// GPM疼痛量表评估逻辑配置文件
import { gpmConfig } from './gpmConfig.js';

export const gpmLogic = {
  // 评估计算规则
  assessmentRules: {
    // GPM总分计算
    calculateGPMScore: (formData) => {
      // 维度一：疼痛强度和频率 (1-5题)
      const dimension1Score = (
        parseInt(formData.restPain || 0) +
        parseInt(formData.activityPain || 0) +
        parseInt(formData.painFrequency || 0) +
        parseInt(formData.nightWakeups || 0) +
        parseInt(formData.painDuration || 0)
      );

      // 维度二：日常生活活动能力 (6-12题)
      const dimension2Score = (
        parseInt(formData.dressingAbility || 0) +
        parseInt(formData.eatingAbility || 0) +
        parseInt(formData.walkingAbility || 0) +
        parseInt(formData.toiletingAbility || 0) +
        parseInt(formData.hygieneAbility || 0) +
        parseInt(formData.sleepQuality || 0) +
        parseInt(formData.houseworkAbility || 0)
      );

      // 维度三：心理情绪状态 (13-18题)
      const dimension3Score = (
        parseInt(formData.anxiety || 0) +
        parseInt(formData.depression || 0) +
        parseInt(formData.irritability || 0) +
        parseInt(formData.helplessness || 0) +
        parseInt(formData.concentration || 0) +
        parseInt(formData.lifeEnjoyment || 0)
      );

      // 维度四：社会功能 (19-22题)
      const dimension4Score = (
        parseInt(formData.socialParticipation || 0) +
        parseInt(formData.familyRole || 0) +
        parseInt(formData.workAbility || 0) +
        parseInt(formData.intimateRelationship || 0)
      );

      // 维度五：疼痛管理 (23-24题)
      const dimension5Score = (
        parseInt(formData.painReliefEffect || 0) +
        parseInt(formData.medicalSeeking || 0)
      );

      const totalScore = dimension1Score + dimension2Score + dimension3Score + dimension4Score + dimension5Score;
      
      // 确定疼痛等级
      let painLevel;
      if (totalScore <= 24) {
        painLevel = gpmConfig.painLevels.mild;
      } else if (totalScore <= 48) {
        painLevel = gpmConfig.painLevels.moderate;
      } else if (totalScore <= 72) {
        painLevel = gpmConfig.painLevels.severe;
      } else {
        painLevel = gpmConfig.painLevels.verySevere;
      }

      return {
        totalScore,
        dimension1Score,
        dimension2Score,
        dimension3Score,
        dimension4Score,
        dimension5Score,
        painLevel: painLevel.name,
        painLevelColor: painLevel.color,
        painLevelRange: painLevel.range,
        description: painLevel.description,
        recommendations: painLevel.recommendations
      };
    },

    // BMI计算
    calculateBMI: (height, weight) => {
      if (!height || !weight || height <= 0 || weight <= 0) {
        return null;
      }
      
      const heightInMeters = height / 100;
      const bmi = weight / (heightInMeters * heightInMeters);
      
      let category;
      if (bmi < 18.5) {
        category = '偏瘦';
      } else if (bmi < 24) {
        category = '正常';
      } else if (bmi < 28) {
        category = '超重';
      } else {
        category = '肥胖';
      }
      
      return {
        value: bmi.toFixed(1),
        category
      };
    },

    // 维度分析
    analyzeDimensions: (formData) => {
      const result = gpmLogic.assessmentRules.calculateGPMScore(formData);
      
      const dimensionAnalysis = {
        dimension1: {
          name: '疼痛强度和频率',
          score: result.dimension1Score,
          maxScore: 20,
          percentage: ((result.dimension1Score / 20) * 100).toFixed(1),
          severity: result.dimension1Score <= 5 ? '轻度' : result.dimension1Score <= 10 ? '中度' : result.dimension1Score <= 15 ? '重度' : '极重度'
        },
        dimension2: {
          name: '日常生活活动能力',
          score: result.dimension2Score,
          maxScore: 28,
          percentage: ((result.dimension2Score / 28) * 100).toFixed(1),
          severity: result.dimension2Score <= 7 ? '轻度' : result.dimension2Score <= 14 ? '中度' : result.dimension2Score <= 21 ? '重度' : '极重度'
        },
        dimension3: {
          name: '心理情绪状态',
          score: result.dimension3Score,
          maxScore: 24,
          percentage: ((result.dimension3Score / 24) * 100).toFixed(1),
          severity: result.dimension3Score <= 6 ? '轻度' : result.dimension3Score <= 12 ? '中度' : result.dimension3Score <= 18 ? '重度' : '极重度'
        },
        dimension4: {
          name: '社会功能',
          score: result.dimension4Score,
          maxScore: 16,
          percentage: ((result.dimension4Score / 16) * 100).toFixed(1),
          severity: result.dimension4Score <= 4 ? '轻度' : result.dimension4Score <= 8 ? '中度' : result.dimension4Score <= 12 ? '重度' : '极重度'
        },
        dimension5: {
          name: '疼痛管理',
          score: result.dimension5Score,
          maxScore: 8,
          percentage: ((result.dimension5Score / 8) * 100).toFixed(1),
          severity: result.dimension5Score <= 2 ? '轻度' : result.dimension5Score <= 4 ? '中度' : result.dimension5Score <= 6 ? '重度' : '极重度'
        }
      };
      
      return dimensionAnalysis;
    }
  },

  // 统计分析规则
  statisticsRules: {
    // 计算疼痛等级分布
    calculatePainLevelDistribution: (surveys) => {
      const distribution = {
        mild: { name: '轻度疼痛', count: 0, percentage: 0, range: '0-24分' },
        moderate: { name: '中度疼痛', count: 0, percentage: 0, range: '25-48分' },
        severe: { name: '重度疼痛', count: 0, percentage: 0, range: '49-72分' },
        verySevere: { name: '极重度疼痛', count: 0, percentage: 0, range: '73-96分' }
      };
      
      const total = surveys.length;
      
      surveys.forEach(survey => {
        const result = gpmLogic.assessmentRules.calculateGPMScore(survey);
        const score = result.totalScore;
        
        if (score <= 24) {
          distribution.mild.count++;
        } else if (score <= 48) {
          distribution.moderate.count++;
        } else if (score <= 72) {
          distribution.severe.count++;
        } else {
          distribution.verySevere.count++;
        }
      });
      
      // 计算百分比
      Object.keys(distribution).forEach(level => {
        distribution[level].percentage = total > 0 ? 
          ((distribution[level].count / total) * 100).toFixed(1) : 0;
      });
      
      return distribution;
    },

    // 计算维度统计
    calculateDimensionStats: (surveys) => {
      const dimensionStats = {
        dimension1: { name: '疼痛强度和频率', total: 0, average: 0, maxScore: 20 },
        dimension2: { name: '日常生活活动能力', total: 0, average: 0, maxScore: 28 },
        dimension3: { name: '心理情绪状态', total: 0, average: 0, maxScore: 24 },
        dimension4: { name: '社会功能', total: 0, average: 0, maxScore: 16 },
        dimension5: { name: '疼痛管理', total: 0, average: 0, maxScore: 8 }
      };
      
      const total = surveys.length;
      
      surveys.forEach(survey => {
        const result = gpmLogic.assessmentRules.calculateGPMScore(survey);
        dimensionStats.dimension1.total += result.dimension1Score;
        dimensionStats.dimension2.total += result.dimension2Score;
        dimensionStats.dimension3.total += result.dimension3Score;
        dimensionStats.dimension4.total += result.dimension4Score;
        dimensionStats.dimension5.total += result.dimension5Score;
      });
      
      // 计算平均值
      Object.keys(dimensionStats).forEach(dimension => {
        dimensionStats[dimension].average = total > 0 ? 
          (dimensionStats[dimension].total / total).toFixed(1) : 0;
      });
      
      return dimensionStats;
    },

    // 计算基本统计信息
    calculateBasicStats: (surveys) => {
      if (surveys.length === 0) {
        return {
          totalCount: 0,
          averageScore: 0,
          minScore: 0,
          maxScore: 0,
          averageAge: 0,
          genderDistribution: { male: 0, female: 0 }
        };
      }
      
      let totalScore = 0;
      let totalAge = 0;
      let minScore = 96;
      let maxScore = 0;
      let maleCount = 0;
      let femaleCount = 0;
      
      surveys.forEach(survey => {
        const result = gpmLogic.assessmentRules.calculateGPMScore(survey);
        totalScore += result.totalScore;
        
        if (result.totalScore < minScore) minScore = result.totalScore;
        if (result.totalScore > maxScore) maxScore = result.totalScore;
        
        if (survey.age) totalAge += parseInt(survey.age);
        
        if (survey.gender === 'male') maleCount++;
        else if (survey.gender === 'female') femaleCount++;
      });
      
      return {
        totalCount: surveys.length,
        averageScore: (totalScore / surveys.length).toFixed(1),
        minScore,
        maxScore,
        averageAge: surveys.length > 0 ? (totalAge / surveys.length).toFixed(1) : 0,
        genderDistribution: {
          male: maleCount,
          female: femaleCount,
          malePercentage: ((maleCount / surveys.length) * 100).toFixed(1),
          femalePercentage: ((femaleCount / surveys.length) * 100).toFixed(1)
        }
      };
    }
  },

  // 报告模板
  reportTemplates: {
    // 个人评估报告
    individualReport: (survey, recorderInfo) => {
      const result = gpmLogic.assessmentRules.calculateGPMScore(survey);
      const bmi = gpmLogic.assessmentRules.calculateBMI(survey.height, survey.weight);
      const dimensionAnalysis = gpmLogic.assessmentRules.analyzeDimensions(survey);
      
      return `# GPM疼痛量表个人评估报告

## 基本信息
- **被评估人姓名**: ${survey.patientName || '未填写'}
- **年龄**: ${survey.age || '未填写'}岁
- **性别**: ${survey.gender === 'male' ? '男性' : survey.gender === 'female' ? '女性' : '未填写'}
- **身高**: ${survey.height || '未填写'}cm
- **体重**: ${survey.weight || '未填写'}kg
- **BMI**: ${bmi ? `${bmi.value} (${bmi.category})` : '未计算'}
- **评估时间**: ${survey.recordTime ? new Date(survey.recordTime).toLocaleString('zh-CN') : '未填写'}
- **记录人**: ${recorderInfo.recorderName || '未填写'}
- **职务/身份**: ${recorderInfo.recorderTitle || '未填写'}

## 评估结果
- **总分**: ${result.totalScore}分 / 96分
- **疼痛等级**: ${result.painLevel} (${result.painLevelRange})
- **等级描述**: ${result.description}

## 各维度得分
### 维度一：疼痛强度和频率
- **得分**: ${result.dimension1Score}分 / 20分 (${dimensionAnalysis.dimension1.percentage}%)
- **严重程度**: ${dimensionAnalysis.dimension1.severity}

### 维度二：日常生活活动能力
- **得分**: ${result.dimension2Score}分 / 28分 (${dimensionAnalysis.dimension2.percentage}%)
- **严重程度**: ${dimensionAnalysis.dimension2.severity}

### 维度三：心理情绪状态
- **得分**: ${result.dimension3Score}分 / 24分 (${dimensionAnalysis.dimension3.percentage}%)
- **严重程度**: ${dimensionAnalysis.dimension3.severity}

### 维度四：社会功能
- **得分**: ${result.dimension4Score}分 / 16分 (${dimensionAnalysis.dimension4.percentage}%)
- **严重程度**: ${dimensionAnalysis.dimension4.severity}

### 维度五：疼痛管理
- **得分**: ${result.dimension5Score}分 / 8分 (${dimensionAnalysis.dimension5.percentage}%)
- **严重程度**: ${dimensionAnalysis.dimension5.severity}

## 主观描述
${survey.painDescription ? `**疼痛描述**: ${survey.painDescription}` : ''}
${survey.priorityImprovement ? `**优先改善需求**: ${survey.priorityImprovement}` : ''}

## 建议措施
${result.recommendations.map(rec => `- ${rec}`).join('\n')}

## 备注
${survey.remarks || '无'}

---
*报告生成时间: ${new Date().toLocaleString('zh-CN')}*
*评估工具: 老年疼痛量表 (GPM)*`;
    },

    // 汇总统计报告
    summaryReport: (surveys, recorderInfo, statistics) => {
      return `# GPM疼痛量表汇总统计报告

## 基本统计信息
- **评估总数**: ${statistics.basic.totalCount}例
- **平均得分**: ${statistics.basic.averageScore}分
- **最低得分**: ${statistics.basic.minScore}分
- **最高得分**: ${statistics.basic.maxScore}分
- **平均年龄**: ${statistics.basic.averageAge}岁

## 性别分布
- **男性**: ${statistics.basic.genderDistribution.male}例 (${statistics.basic.genderDistribution.malePercentage}%)
- **女性**: ${statistics.basic.genderDistribution.female}例 (${statistics.basic.genderDistribution.femalePercentage}%)

## 疼痛等级分布
- **轻度疼痛 (0-24分)**: ${statistics.painLevel.mild.count}例 (${statistics.painLevel.mild.percentage}%)
- **中度疼痛 (25-48分)**: ${statistics.painLevel.moderate.count}例 (${statistics.painLevel.moderate.percentage}%)
- **重度疼痛 (49-72分)**: ${statistics.painLevel.severe.count}例 (${statistics.painLevel.severe.percentage}%)
- **极重度疼痛 (73-96分)**: ${statistics.painLevel.verySevere.count}例 (${statistics.painLevel.verySevere.percentage}%)

## 各维度平均得分
- **维度一 (疼痛强度和频率)**: ${statistics.dimensions.dimension1.average}分 / ${statistics.dimensions.dimension1.maxScore}分
- **维度二 (日常生活活动能力)**: ${statistics.dimensions.dimension2.average}分 / ${statistics.dimensions.dimension2.maxScore}分
- **维度三 (心理情绪状态)**: ${statistics.dimensions.dimension3.average}分 / ${statistics.dimensions.dimension3.maxScore}分
- **维度四 (社会功能)**: ${statistics.dimensions.dimension4.average}分 / ${statistics.dimensions.dimension4.maxScore}分
- **维度五 (疼痛管理)**: ${statistics.dimensions.dimension5.average}分 / ${statistics.dimensions.dimension5.maxScore}分

## 记录人信息
- **记录人**: ${recorderInfo.recorderName || '未填写'}
- **职务/身份**: ${recorderInfo.recorderTitle || '未填写'}
- **联系方式**: ${recorderInfo.recorderContact || '未填写'}

---
*报告生成时间: ${new Date().toLocaleString('zh-CN')}*
*评估工具: 老年疼痛量表 (GPM)*
*数据来源: ${statistics.basic.totalCount}例GPM疼痛量表评估*`;
    },

    // 详细CSV数据
    detailsCSV: (surveys) => {
      const headers = [
        '问答编号', '被评估人姓名', '年龄', '性别', '身高(cm)', '体重(kg)', 'BMI', 'BMI分类',
        '评估时间', '总分', '疼痛等级',
        '维度一得分', '维度二得分', '维度三得分', '维度四得分', '维度五得分',
        '静息疼痛', '活动疼痛', '疼痛频率', '夜间痛醒', '疼痛持续时间',
        '穿衣能力', '进食能力', '行走能力', '如厕能力', '洗漱能力', '睡眠质量', '家务活动',
        '焦虑情绪', '抑郁情绪', '易怒倾向', '无助感', '注意力集中', '生活乐趣',
        '社交参与', '家庭角色', '工作能力', '亲密关系',
        '疼痛缓解效果', '就医主动性',
        '疼痛描述', '优先改善需求', '备注'
      ];
      
      const rows = surveys.map(survey => {
        const result = gpmLogic.assessmentRules.calculateGPMScore(survey);
        const bmi = gpmLogic.assessmentRules.calculateBMI(survey.height, survey.weight);
        
        return [
          survey.surveyId || '',
          survey.patientName || '',
          survey.age || '',
          survey.gender === 'male' ? '男性' : survey.gender === 'female' ? '女性' : '',
          survey.height || '',
          survey.weight || '',
          bmi ? bmi.value : '',
          bmi ? bmi.category : '',
          survey.recordTime ? new Date(survey.recordTime).toLocaleString('zh-CN') : '',
          result.totalScore,
          result.painLevel,
          result.dimension1Score,
          result.dimension2Score,
          result.dimension3Score,
          result.dimension4Score,
          result.dimension5Score,
          survey.restPain || 0,
          survey.activityPain || 0,
          survey.painFrequency || 0,
          survey.nightWakeups || 0,
          survey.painDuration || 0,
          survey.dressingAbility || 0,
          survey.eatingAbility || 0,
          survey.walkingAbility || 0,
          survey.toiletingAbility || 0,
          survey.hygieneAbility || 0,
          survey.sleepQuality || 0,
          survey.houseworkAbility || 0,
          survey.anxiety || 0,
          survey.depression || 0,
          survey.irritability || 0,
          survey.helplessness || 0,
          survey.concentration || 0,
          survey.lifeEnjoyment || 0,
          survey.socialParticipation || 0,
          survey.familyRole || 0,
          survey.workAbility || 0,
          survey.intimateRelationship || 0,
          survey.painReliefEffect || 0,
          survey.medicalSeeking || 0,
          survey.painDescription || '',
          survey.priorityImprovement || '',
          survey.remarks || ''
        ];
      });
      
      return [headers, ...rows];
    },

    // 当前评估报告
    assessmentReport: (formData, recorderInfo) => {
      return gpmLogic.reportTemplates.individualReport({
        ...formData,
        surveyId: recorderInfo.surveyId
      }, recorderInfo);
    }
  },

  // 生成汇总报告
  generateSummaryReport: (surveys, statistics, recorderInfo) => {
    return gpmLogic.reportTemplates.summaryReport(surveys, recorderInfo, statistics);
  },

  // 生成详细CSV
  generateDetailedCSV: (surveys) => {
    return gpmLogic.reportTemplates.detailsCSV(surveys);
  },

  // 生成个人报告
  generateIndividualReport: (survey, recorderInfo) => {
    return gpmLogic.reportTemplates.individualReport(survey, recorderInfo);
  }
};

// 计算GPM评估结果
export const calculateGPMAssessment = (formData) => {
  const result = gpmLogic.assessmentRules.calculateGPMScore(formData);
  const bmi = gpmLogic.assessmentRules.calculateBMI(formData.height, formData.weight);
  const dimensionAnalysis = gpmLogic.assessmentRules.analyzeDimensions(formData);
  
  return {
    ...result,
    bmi,
    dimensionAnalysis
  };
};

// 计算GPM统计数据
export const calculateGPMStatistics = (surveys) => {
  return {
    basic: gpmLogic.statisticsRules.calculateBasicStats(surveys),
    painLevel: gpmLogic.statisticsRules.calculatePainLevelDistribution(surveys),
    dimensions: gpmLogic.statisticsRules.calculateDimensionStats(surveys)
  };
};